package com.itheima.leyou.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itheima.leyou.dao.StockDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class StockService {

    @Resource
    private StockDao stockDao;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RestTemplate restTemplate;

    public Map<String, Object> getStockList(){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        //1、从stockDao里取数据
        ArrayList<Map<String, Object>> list = stockDao.getStockList();

        //2、判断取出的数据是否为空
        if (list==null||list.isEmpty()){
            resultMap.put("result", false);
            resultMap.put("msg", "数据库都没有取出数据！");
            return resultMap;
        }

        //3、从redis里取政策
        resultMap = getRedisPolicy(list);

        //4、返回数据
//        resultMap.put("result", true);
//        resultMap.put("msg", "");
        resultMap.put("sku_list", list);
        return resultMap;
    }


    public Map<String, Object> getStock(String sku_id){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        //1、从stockDao里取数据
        ArrayList<Map<String, Object>> list = stockDao.getStock(sku_id);

        //2、判断取出的数据是否为空
        if (list==null||list.isEmpty()){
            resultMap.put("result", false);
            resultMap.put("msg", "数据库都没有取出数据！");
            return resultMap;
        }

        //3、从redis里取政策
        resultMap = getRedisPolicy(list);

        //4、返回数据
//        resultMap.put("result", true);
//        resultMap.put("msg", "");
        resultMap.put("sku", list);
        return resultMap;
    }

    @Transactional
    public Map<String, Object> insertLimitPolicy(Map<String, Object> map){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        //1、传入的参数有误时，返回错误信息
        if (map==null||map.isEmpty()){
            resultMap.put("result", false);
            resultMap.put("msg", "传入的什么东东？");
            return resultMap;
        }

        //2、调用stockDao的insertLimitPolicy方法写入数据库
        boolean result = stockDao.insertLimitPolicy(map);

        //3、判断写入是否失败
        if (!result){
            resultMap.put("result", false);
            resultMap.put("msg", "数据库咋还执行失败了呢？");
            return resultMap;
        }

        //4、写入redis
        long diff = 0;

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        //控制有效期，政策结束日期 减去 当前时间 作为 redis 的有效期
        String now = restTemplate.getForObject("http://leyou-time-server/getTime", String.class);
        try {
            Date end_time = simpleDateFormat.parse(map.get("end_time").toString());
            Date now_time = simpleDateFormat.parse(now);

            diff = (end_time.getTime() - now_time.getTime())/1000;
            if (diff<0){
                resultMap.put("result", false);
                resultMap.put("msg", "结束时间不能小于当前时间！");
                return resultMap;
            }

        } catch (ParseException e) {
            resultMap.put("result", false);
            resultMap.put("msg", "日期转换错误！"+e.getMessage());
            return resultMap;
        }
        String sku_id = map.get("sku_id").toString();

        stringRedisTemplate.delete("LIMIT_POLICY_"+sku_id);
        String json = JSON.toJSONString(map);
        stringRedisTemplate.opsForValue().set("LIMIT_POLICY_"+sku_id, json, diff);


        stringRedisTemplate.delete("SKU_"+sku_id);
        ArrayList<Map<String, Object>> list = stockDao.getStock(sku_id);
        String skuObj = JSON.toJSONString(list.get(0));
        stringRedisTemplate.opsForValue().set("SKU_"+sku_id, skuObj, diff);

        //5、返回数据
        resultMap.put("result", true);
        resultMap.put("msg", "");
        return resultMap;
    }


    private Map<String, Object> getRedisPolicy(ArrayList<Map<String, Object>> list){
        Map<String, Object> resultMap = new HashMap<String, Object>();

        for (Map<String, Object> skuMap: list){
            String sku_id = skuMap.get("sku_id").toString();
            String limitPolicy = stringRedisTemplate.opsForValue().get("LIMIT_POLICY_"+sku_id);

            if (limitPolicy!=null&&!limitPolicy.equals("")){
                Map<String, Object> limitPolicyMap = JSONObject.parseObject(limitPolicy);

                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                String now = restTemplate.getForObject("http://leyou-time-server/getTime", String.class);
                //4、判断当前时间大于开始时间，则政策有效
                try {
                    Date begin_time = simpleDateFormat.parse(limitPolicyMap.get("begin_time").toString());
                    Date now_time = simpleDateFormat.parse(now);

                    //5、将政策的值写入list
                    if (now_time.getTime()>=begin_time.getTime()){
                        skuMap.put("limitPrice", limitPolicyMap.get("price"));
                        skuMap.put("limitQuanty", limitPolicyMap.get("quanty"));
                        skuMap.put("limitBeginTime", limitPolicyMap.get("begin_time"));
                        skuMap.put("limitEndTime", limitPolicyMap.get("end_time"));
                        skuMap.put("nowTime", now);
                    }

                } catch (ParseException e) {
                    resultMap.put("result", false);
                    resultMap.put("msg", "时间转换失败！"+e.getMessage());
                    return resultMap;
                }

            }
        }

        resultMap.put("result", true);
        resultMap.put("msg", "");
        return resultMap;
    }

}
